﻿using FreeSql;

namespace D.UtilFreesqlOrm
{
    /// <summary>
    /// FreeSQL 事务和工作单元
    /// </summary>
    public sealed class FreesqlUnitOfWork : IFreesqlUnitOfWork
    {
        private readonly IFreeSql _freeSql;
        private IUnitOfWork _unitOfWork;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="freeSql">FreeSQL 实例</param>
        public FreesqlUnitOfWork(IFreeSql freeSql)
        {
            Console.WriteLine($"初始化事务工作单元:{freeSql.Ado.MasterPool.Get().Id}");
            _freeSql = freeSql ?? throw new ArgumentNullException(nameof(freeSql));
        }

        /// <summary>
        /// 开启事务
        /// </summary>
        public void BeginTransaction()
        {
            try
            {
                if (_unitOfWork != null)
                {
                    throw new InvalidOperationException("事务已开启，不能重复开启。");
                }

                _unitOfWork = _freeSql.CreateUnitOfWork();
                Console.WriteLine("事务已开启。");
            }
            catch (Exception ex)
            {
                throw new Exception("开启事务出错", ex);
            }
        }

        /// <summary>
        /// 提交事务
        /// </summary>
        public void CommitTransaction()
        {
            try
            {
                if (_unitOfWork == null)
                {
                    throw new InvalidOperationException("当前没有活动的事务，无法提交。");
                }
                Console.WriteLine($"提交事务：{_freeSql.Ado.MasterPool.Get().Id}");
                _unitOfWork.Commit();
                Console.WriteLine("事务已提交。");
            }
            catch (Exception ex)
            {
                throw new Exception("提交事务出错", ex);
            }
        }

        /// <summary>
        /// 回滚事务
        /// </summary>
        public void RollbackTransaction()
        {
            try
            {
                Console.WriteLine($"回滚事务：{_freeSql.Ado.MasterPool.Get().Id}");
                if (_unitOfWork == null)
                {
                    throw new InvalidOperationException("当前没有活动的事务，无法回滚。");
                }
                _unitOfWork.Rollback();
                Console.WriteLine("事务已回滚。");
            }
            catch (Exception ex)
            {
                throw new Exception("回滚事务时出错", ex);
            }
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void OnDispose()
        {
            Console.WriteLine($"释放连接：{_freeSql.Ado.MasterPool.Get().Id}");

            if (_unitOfWork != null)
            {
                _unitOfWork.Dispose();
                _unitOfWork = null;
            }
            Console.WriteLine("资源已释放。");
        }
    }
}
